using System.Web.Mvc;
using Dinner.Models;

namespace Dinner.Controllers
{
	public class ItemController : Controller
	{
		ItemRepository itemRepository = new ItemRepository(); 

		//
		// GET: /Item/

		public ActionResult Index()
		{
			var items = itemRepository.FindAllItems();

			return View(items);
		}

		//
		// GET: /Item/Details/5

		public ActionResult Details(int id)
		{
			Item item = itemRepository.GetItem(id);

			if (item == null)
				return View("NotFound");
			else
				return View(item);
		}

		//
		// GET: /Item/Create

		public ActionResult Create()
		{
			return View();
		} 

		//
		// POST: /Item/Create

		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult Create(FormCollection collection)
		{
			Item item = new Item();
			try
			{
				UpdateModel(item);

				itemRepository.Add(item);
				itemRepository.Save();

				return RedirectToAction("Index");
			}
			catch
			{
				ModelState.AddRuleViolations(item.GetRuleViolations());
				return View(item);
			}
		}

		//
		// GET: /Item/Edit/5
 
		public ActionResult Edit(int id)
		{
			Item item = itemRepository.GetItem(id);

			return View(item);
		}

		//
		// POST: /Item/Edit/5

		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult Edit(int id, FormCollection collection)
		{
			Item item = itemRepository.GetItem(id);

			try
			{
				UpdateModel(item);
				itemRepository.Save();
				return RedirectToAction("Details", new { id = item.item_id });
			}
			catch
			{
				ModelState.AddRuleViolations(item.GetRuleViolations());
				return View(item);
			}
		}
	}
}
